<?php

namespace App\Http\Controllers\Admin;

use App\Models\NavigationArea;
use App\Models\NavigationPoint;
use App\Validate\NavigationAreaValidate;
use Illuminate\Support\Facades\DB;

/**
 * 室内导航区域配置
 */
class NavigationAreaController extends CommonController
{
    protected $model;
    protected $validate;

    public function __construct()
    {
        parent::__construct();

        $this->model = new NavigationArea();
        $this->validate = new  NavigationAreaValidate();
    }
    /**
     * 筛选列表
     * @param build_id int 所属建筑id
     * @param except_id int  要排除的id。选择过渡区域使用
     */
    public function filterList()
    {
        if (!$this->validate->scene('list')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        $build_id = $this->request->build_id;
        $except_id = $this->request->except_id;
        $res = $this->model->filterList($build_id, $except_id);

        if (empty($res)) {
            return $this->returnApi(203, '暂无数据');
        }
        return $this->returnApi(200, '查询成功', true, $res);
    }
    /**
     * 列表
     * @param build_id int 所属建筑id
     * @param page int 页码
     * @param limit int 分页大小
     * @param level_id int 区域等级 1一级区域 2有索书号的区域 默认查所有
     * @param keywords string 搜索关键词
     */
    public function lists()
    {
        if (!$this->validate->scene('list')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $build_id = $this->request->build_id;
        $level_id = $this->request->level_id;
        $keywords = $this->request->keywords;
        $res = $this->model->lists($build_id, $level_id, $keywords, $limit);
        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }
        $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);
        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 区域id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        $id = $this->request->id;
        $res = $this->model->where('id', $id)->where('is_del', 1)->first();
        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        return $this->returnApi(200, "查询成功", true, $res->toArray());
    }
    /**
     * 新增
     * @param name string 区域名称
     * @param alias_name string 区域别名
     * @param build_id string  所属建筑id
     * @param is_start int 是否起点区域 1是 2不是
     * @param level  区域等级 1顶级 2有索书号的 默认1
     * @param img string 区域图片
     * @param rotation_angle string 指北针 偏移角度  0~360
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        $name = $this->request->name;
        $build_id = $this->request->build_id;
        $level = !empty($this->request->level) ? $this->request->level : 1;
        $img = $this->request->img;
        $is_start = $this->request->is_start;

        $findWhere[] = ['build_id', $build_id];
        $is_exists = $this->model->nameIsExists($name, 'name', '', 1, $findWhere);
        if ($is_exists) {
            return $this->returnApi(202, "该区域名称已存在");
        }
        if ($img) {
            //检查图片格式是否正确
            $check = $this->model->checkSvgImg($img);
            if ($check['code'] != 200) return $this->returnApi(202, $check['msg']);
        }
        if ($is_start == 1) {
            //区域起点只能有一个，如果设置了起点，则其他需要修改
            $this->model->checkIsStartData($build_id);
        }
        $data = $this->request->all();
        $data['level'] = $level;
        $res = $this->model->add($data);
        if (!$res) {
            return $this->returnApi(202, "新增失败");
        }
        return $this->returnApi(200, "新增成功", true);
    }

    /**
     * 编辑
     * @param id string 区域id
     * @param name string 区域名称
     * @param alias_name string 区域别名
     * @param build_id string  所属建筑id
     * @param level  区域等级 1顶级 2有索书号的 默认1
     * @param is_start int 是否起点区域 1是 2不是
     * @param img string 区域图片
     * @param rotation_angle string 指北针 偏移角度  0~360
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        $id = $this->request->id;
        $name = $this->request->name;
        $build_id = $this->request->build_id;
        $img = $this->request->img;
        $is_start = $this->request->is_start;

        $findWhere[] = ['build_id', $build_id];
        $is_exists = $this->model->nameIsExists($name, 'name', $this->request->id, 1, $findWhere);
        if ($is_exists) {
            return $this->returnApi(202, "该区域名称已存在");
        }

        $old_data = $this->model->where('id', $id)->where('is_del', 1)->first();
        if (!$old_data) {
            return $this->returnApi(201, "参数传递错误");
        }
        if ($img != $old_data->img) {
            //图片不是同一张，验证格式
            $check = $this->model->checkSvgImg($img);
            if ($check['code'] != 200) return $this->returnApi(202, $check['msg']);
        }
        // 启动事务
        DB::beginTransaction();
        try {
            if ($is_start == 1) {
                //区域起点只能有一个，如果设置了起点，则其他需要修改
                $this->model->checkIsStartData($build_id, $id);
            }
            $this->model->change($this->request->all());
            // 提交事务
            DB::commit();
            if ($old_data->img != $img) {
                //删除旧图片
                $this->deleteFile($old_data->img);
            }
            return $this->returnApi(200, "保存成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 删除
     * @param id int 区域id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        $id = $this->request->id;
        //先查询下面是否有点位，有的话需要先删除
        $pointModel = new NavigationPoint();
        $point_data = $pointModel->where('area_id', $id)->where('is_del', 1)->count();
        if ($point_data) {
            return $this->returnApi(202, "区域下还有点位存在，请先删除点位");
        }
        $res = $this->model->del($this->request->id);
        if ($res) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }

    /**
     * 发布与取消发布
     * @param ids 区域id，多个用逗号拼接   all 是，其余字符  ids 必传
     * @param is_play 是否发布  1.发布  2.未发布  默认2
     */
    public function playAndCancel()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('play_and_cancel')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        list($code, $msg) = $this->model->resumeAndCancel($this->request->ids, 'is_play', $this->request->is_play);

        $is_play = $this->request->is_play == 1 ? '发布' : '取消发布';
        if ($code === 200) {
            return $this->returnApi(200, $is_play . $msg, true);
        }
        return $this->returnApi($code, $is_play . $msg);
    }

    /**
     * 修改区域排序
     * content json格式数据  [{"id":1,"sort":2},{"id":2,"sort":2},{"id":3,"sort":3},{"id":4,"sort":4},{"id":5,"sort":5}]   第一个 sort 最大
     */
    public function sortChange()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('sort_change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $content = $this->request->input('content', '');
        if (empty($content)) {
            return $this->returnApi(201, "参数传递错误");
        }
        $content = json_decode($content, true);

        DB::beginTransaction();
        try {
            foreach ($content as $key => $val) {
                $this->model->where('id', $val['id'])->update(['sort' => $val['sort']]);
            }
            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
